# 使用pygame模块
# 实现植物大战僵尸中十五个僵尸在背景图片中动态行走。鼠标变成锤子之后点击僵尸，僵尸消失死亡并掉落太阳。十五个僵尸都死亡后胜利并出现奖杯图片。每点击一个僵尸都会加一分，一共十五分。如果僵尸走到屏幕最左边之后则游戏失败，出现脑子被吃掉的图片
# 图片路径：images/普通/1.png到22.png共22张图片
# 背景图片：images/beijing.jpg
# 锤子图片：images/hammer.png
# 太阳图片：images/sun/1.png到22.png共22张图片
# 奖杯图片：images/trophy_hi_res.png
# 失败图片：images/ZombiesWon.jpg

import pygame
import os
import random

# 初始化pygame
pygame.init()

# 设置窗口大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Plants vs Zombies - Zombie Walking")

# 关键修改：隐藏系统默认鼠标光标
pygame.mouse.set_visible(False)

# 加载背景图片（缩放至窗口大小）
background_image = None
if os.path.exists("images/beijing.jpg"):
    background_image = pygame.image.load("images/beijing.jpg").convert()
    background_image = pygame.transform.scale(background_image, (screen_width, screen_height))
else:
    print("警告: 找不到背景图片 images/beijing.jpg")

# 加载锤子图片
hammer_image = None
if os.path.exists("images/hammer.png"):
    hammer_image = pygame.image.load("images/hammer.png").convert_alpha()
else:
    print("警告: 找不到锤子图片 images/hammer.png")

# 加载奖杯图片
trophy_image = None
if os.path.exists("images/trophy_hi_res.png"):
    trophy_image = pygame.image.load("images/trophy_hi_res.png").convert_alpha()
else:
    print("警告: 找不到奖杯图片 images/trophy_hi_res.png")

# 加载失败图片
game_over_image = None
if os.path.exists("images/ZombiesWon.jpg"):
    game_over_image = pygame.image.load("images/ZombiesWon.jpg").convert()
else:
    print("警告: 找不到失败图片 images/ZombiesWon.jpg")

# 加载僵尸行走动画帧
zombie_frames = []
for i in range(1, 23):  # 1.png 到 22.png 共22张图片
    frame_path = f"images/普通/{i}.png"
    if os.path.exists(frame_path):
        image = pygame.image.load(frame_path).convert_alpha()
        zombie_frames.append(image)
    else:
        print(f"警告: 找不到图片 {frame_path}")

# 检查是否成功加载了帧
if not zombie_frames:
    print("错误: 没有找到任何僵尸动画帧")
    exit()

# 加载太阳动画帧
sun_frames = []
for i in range(1, 23):  # 1.png 到 22.png 共22张图片
    frame_path = f"images/sun/{i}.png"
    if os.path.exists(frame_path):
        image = pygame.image.load(frame_path).convert_alpha()
        sun_frames.append(image)
    else:
        print(f"警告: 找不到图片 {frame_path}")

# 创建十五个僵尸实例
zombies = []
for i in range(15):
    zombie = {
        'x': screen_width + random.randint(0, 800),  # 随机起始位置
        'y': random.randint(50, screen_height - 150),  # 随机Y轴位置
        'speed': random.uniform(0.5, 1.5),  # 随机速度
        'current_frame': random.randint(0, len(zombie_frames) - 1),
        'last_update': pygame.time.get_ticks(),
        'alive': True
    }
    zombies.append(zombie)

# 太阳列表（含创建时间，用于0.5秒消失）
suns = []

# 游戏状态
score = 0
game_state = "playing"  # playing, win, lose
font = pygame.font.Font(None, 36)

# 动画参数
frame_delay = 150  # 每帧持续时间(毫秒)
sun_lifetime = 500  # 太阳存在时间（毫秒），0.5秒

# 主循环
running = True
clock = pygame.time.Clock()

while running:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN and game_state == "playing":
            # 检查是否点击到僵尸
            mouse_x, mouse_y = event.pos
            for zombie in zombies:
                if zombie['alive']:
                    # 简单的碰撞检测
                    zombie_rect = pygame.Rect(zombie['x'], zombie['y'], 100, 100)
                    if zombie_rect.collidepoint(mouse_x, mouse_y):
                        zombie['alive'] = False
                        score += 1

                        # 创建太阳（记录生成时间）
                        sun = {
                            'x': zombie['x'],
                            'y': zombie['y'],
                            'current_frame': 0,
                            'last_update': pygame.time.get_ticks(),
                            'create_time': pygame.time.get_ticks()
                        }
                        suns.append(sun)

                        break  # 一次只击杀一个僵尸

    # 检查游戏状态
    if game_state == "playing":
        alive_zombies = sum(1 for z in zombies if z['alive'])
        if alive_zombies == 0:
            game_state = "win"
        else:
            # 检查是否有僵尸到达屏幕最左端
            for zombie in zombies:
                if zombie['alive'] and zombie['x'] < 0:
                    game_state = "lose"
                    break

    # 更新动画帧
    current_time = pygame.time.get_ticks()

    # 更新僵尸动画帧
    if game_state == "playing":
        for zombie in zombies:
            if zombie['alive'] and current_time - zombie['last_update'] > frame_delay:
                zombie['current_frame'] = (zombie['current_frame'] + 1) % len(zombie_frames)
                zombie['last_update'] = current_time

            # 移动僵尸
            if zombie['alive']:
                zombie['x'] -= zombie['speed']

    # 更新太阳动画帧 + 超时消失
    for sun in suns[:]:
        if current_time - sun['last_update'] > frame_delay:
            sun['current_frame'] = (sun['current_frame'] + 1) % len(sun_frames)
            sun['last_update'] = current_time
        if current_time - sun['create_time'] > sun_lifetime:
            suns.remove(sun)

    # 绘制
    if background_image:
        screen.blit(background_image, (0, 0))
    else:
        screen.fill((135, 206, 235))  # 填充天空蓝背景

    # 绘制所有僵尸
    if game_state == "playing":
        for zombie in zombies:
            if zombie['alive']:
                screen.blit(zombie_frames[zombie['current_frame']], (zombie['x'], zombie['y']))

    # 绘制太阳
    for sun in suns:
        screen.blit(sun_frames[sun['current_frame']], (sun['x'], sun['y']))

    # 显示分数
    score_text = font.render(f"Score: {score}/15", True, (0, 0, 0))
    screen.blit(score_text, (10, 10))

    # 根据游戏状态绘制相应画面
    if game_state == "win":
        if trophy_image:
            screen.blit(trophy_image, (screen_width // 2 - trophy_image.get_width() // 2,
                                       screen_height // 2 - trophy_image.get_height() // 2))
        win_text = font.render("You Win!", True, (255, 0, 0))
        screen.blit(win_text, (screen_width // 2 - 50, screen_height // 2 - 100))
    elif game_state == "lose":
        if game_over_image:
            screen.blit(game_over_image, (screen_width // 2 - game_over_image.get_width() // 2,
                                          screen_height // 2 - game_over_image.get_height() // 2))
        lose_text = font.render("Game Over!", True, (255, 0, 0))
        screen.blit(lose_text, (screen_width // 2 - 70, screen_height // 2 - 100))

    # 绘制锤子光标（游戏进行中显示）
    if game_state == "playing" and hammer_image:
        mouse_pos = pygame.mouse.get_pos()
        screen.blit(hammer_image, mouse_pos)

    # 更新显示
    pygame.display.flip()
    clock.tick(60)  # 限制帧率为60FPS

pygame.quit()